﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using SmallBusinessKit.DataAccess.Interfaces;

namespace SmallBusinessKit.DataAccess.Infrastructure
{
    public abstract class RepositoryBase<T> : IRepository<T> where T : class
    {
        #region Properties

        private readonly SmallBusinessContext   _dataContext;
        private readonly DbSet<T> 	            _dbset;

        #endregion

        #region Methods

        protected RepositoryBase(IDatabaseFactory databaseFactory)
        {
            _dataContext     = databaseFactory.GetContext();
            _dbset           = _dataContext.Set<T>();
        }

        public virtual T GetById(string id)
        {
            return _dbset.Find(id);
        }

        public T Get(Expression<Func<T, bool>> clause)
        {
            return _dbset.FirstOrDefault(clause);
        }

        public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> clause)
        {
            try
            {
                return _dbset.Where(clause).ToList();
            }
            catch (Exception ex)
            {
                return new List<T>();
            }
        }

        public virtual IEnumerable<T> GetAll()
        {
            return _dbset.ToList();
        }

        public virtual IQueryable<T>  GetAsQueryable()
        {
            return _dbset.AsQueryable();
        }

        #endregion
    }
}
